"""
AUC
"""
import numpy as np
from keras.metrics import AUC


def get_data():
    """

    :return:
    """
    y_true = [0, 0, 1, 1]
    y_pred = [0, 0.5, 0.3, 0.9]
    return y_true, y_pred


def compute_auc(y_true, y_pred):
    """
    auc = sum(I(P_t, P_f)) / (T * F)

    I(P_t, P_f) =  1 if P_t > P_f
    I(P_t, P_f) =  0.5 if P_t = P_f
    I(P_t, P_f) =  0 if P_t < P_f
    :param y_true:
    :param y_pred:
    :return:
    """
    sample_pos = y_true.count(1)
    sample_neg = y_true.count(0)

    p_idx = np.where(np.array(y_true) == 1)[0]
    n_idx = np.where(np.array(y_true) == 0)[0]

    i_info = 0
    # 排列组合
    for i in p_idx:
        for j in n_idx:
            if y_pred[i] > y_pred[j]:
                mid_i_info = 1
            elif y_pred[i] == y_pred[j]:
                mid_i_info = 0.5
            else:
                mid_i_info = 0
            i_info += mid_i_info

    return i_info / (sample_pos * sample_neg)


def run():
    """
    主程序
    :return:
    """
    y_true, y_pred = get_data()

    my_auc = compute_auc(y_true=y_true, y_pred=y_pred)

    auc = AUC()
    auc.update_state(y_true=y_true, y_pred=y_pred)

    info = 'my: {}, auc: {}'.format(my_auc, auc.result())
    print(info)


if __name__ == '__main__':
    run()
